package com.dangdi.show.util;


import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @??? DangD
 * @???? User
 * @??? 2018??6??22?? ????10:09:23
 * @???? HttpClientUtil
 * @·??
 */
public class HttpClientUtil {

    public static HttpResponse HttoPost(String url, Map<String, Object> params) throws URISyntaxException, IOException {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost();
        request.setURI(new URI(url));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }
        request.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        HttpResponse response = client.execute(request);
        return response;
    }


    public static Map<String, Object> HttoGet(String url) {
        Map<String, Object> map = new HashMap<>();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
//             创建httpget.
            HttpGet httpget = new HttpGet(url);
//            System.out.println("executing request " + httpget.getURI());
            // 执行get请求.
            response = httpclient.execute(httpget);
            try {
//                // 获取响应实体
                HttpEntity entity = response.getEntity();
//                System.out.println("--------------------------------------");
                // 打印响应状态
//                System.out.println(response.getStatusLine());
//                if (entity != null) {
////                     打印响应内容长度
//                    System.out.println("Response content length: " + entity.getContentLength());
////                     打印响应内容
                map.put("entity", EntityUtils.toString(entity));
                map.put("response", response);
//                }
//                System.out.println("------------------------------------");
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    // 使用POST方法发送XML数据
    public static HttpResponse sendXMLDataByPost(String url, String xmlData) throws Exception {
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "text/xml");
//        post.setHeader("charset","utf-8");
        String newXmlData = new String(xmlData.getBytes(), "utf-8");
        List<BasicNameValuePair> parameters = new ArrayList<>();
        post.setEntity(new StringEntity(newXmlData, "UTF-8"));
        HttpResponse response = client.execute(post);
        return response;
    }

    public static HttpResponse refondPost(String url, String xmlParam) throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException {
        StringBuilder sb = new StringBuilder();
        CloseableHttpResponse response = null;
        try {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream instream = new FileInputStream(new File("C:/data/diangener/cert/apiclient_cert.p12"));
            try {
                keyStore.load(instream, "1518556491".toCharArray());
            } finally {
                instream.close();
            }

            // 证书
            SSLContext sslcontext = SSLContexts.custom()
                    .loadKeyMaterial(keyStore, "1518556491".toCharArray())
                    .build();
            // 只允许TLSv1协议
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslcontext,
                    new String[]{"TLSv1"},
                    null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            //创建基于证书的httpClient,后面要用到
            CloseableHttpClient client = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build();

            HttpPost httpPost = new HttpPost(url);//退款接口
            StringEntity reqEntity = new StringEntity(xmlParam);
            // 设置类型
            reqEntity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(reqEntity);
            response = client.execute(httpPost);
            return response;
        } catch (Exception e) {

        }
        return response;
    }
}
